package com.lyf.shop.web.controller.admin;

import com.alibaba.fastjson.JSON;
import com.lyf.shop.common.Const;
import com.lyf.shop.entity.User;
import com.lyf.shop.services.Impl.UserServiceImpl;
import com.lyf.shop.services.UserService;
import com.lyf.shop.util.MD5Utils;
import com.lyf.shop.web.controller.BaseController;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/admin")
public class AdminUserController extends BaseController {
    private UserService userService = new UserServiceImpl();

    /**
     * 删除
     * @param request
     * @param response
     * @return
     */
    public String deleteUser(HttpServletRequest request, HttpServletResponse response){
        Integer uid = Integer.valueOf(request.getParameter("uid"));
        int i = userService.deleteUser(uid);
        if(i>0){
            return "删除成功";
        }else {
            return "删除失败";
        }
    }

    /**
     *
     * @param request
     * @param response
     * @return
     */
    public String getUserList(HttpServletRequest request, HttpServletResponse response){
        /*
            查询条件有两个
            uname ==>  模糊查询
            usex ==>  查询
            1. uname like %s%

         */
        String uname = request.getParameter("uname");
        String usex = request.getParameter("usex");
        List<User> users = userService.userList(uname,usex);
        String s = JSON.toJSONString(users);
        return s;
    }

    /**
     * 注销登录的动作
     * @param request
     * @param response
     * @return
     */
    public String adminLogout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("admin");//清除session某个值
        return Const.REDIRECT+"/admin/login.jsp";
    }

    /**
     * 管理员登录
     * @param request
     * @param response
     * @return
     */
    public String adminLogin(HttpServletRequest request, HttpServletResponse response){
        String uname = request.getParameter("uname");
        String upassword = request.getParameter("upassword");

        User user = userService.findUserByUname(uname);
        if(user!=null){
            //有这个用户
            if(user.getUrole()!=1){
                request.getSession().setAttribute("msg","只有管理员能登录");
                return Const.REDIRECT+"/admin/login.jsp";
            }
            if(user.getUpassword().equals(MD5Utils.md5(upassword))){
                //session的用户信息保存呢
                request.getSession().setAttribute("admin",user);//把登录管理员的数据进行保存
                System.out.println(user);
                return Const.REDIRECT+"/admin/admin.jsp";
            }
        }
        request.getSession().setAttribute("msg","用户名或密码错误");
        return Const.REDIRECT+"/admin/login.jsp";
    }
}
